import { useEffect, useState } from "react";
import { Card } from "antd";
import axios from "axios";
import {
  Chart as ChartJS,
  ArcElement,
  BarElement,
  LineElement,
  CategoryScale,
  LinearScale,
  PointElement,
  Title,
  Tooltip,
  Legend,
} from "chart.js";
import { Pie, Bar, Line } from "react-chartjs-2";
import * as echarts from "echarts";
import dayjs from "dayjs";
import { DatePicker } from "antd";
const { RangePicker } = DatePicker;
const mockOrderStats = {
  total: 145,
  statusDistribution: [
    { status: "已支付", count: 100 },
    // { status: '已完成', count: 180 },
    { status: "未支付", count: 45 },
  ],
  trend: Array.from({ length: 30 }, (_, i) => ({
    date: dayjs()
      .subtract(29 - i, "days")
      .format("YYYY-MM-DD"),
    count: Math.floor(Math.random() * 100) + 50,
  })),
};

// 模拟测算统计数据
const mockFortuneStats = {
  total: 4780,
  typeDistribution: [
    { fortune_type: "八字测算", count: 2200 },
    { fortune_type: "1234", count: 1500 },
    { fortune_type: "5678", count: 1080 },
  ],
  trend: Array.from({ length: 30 }, (_, i) => ({
    date: dayjs()
      .subtract(29 - i, "days")
      .format("YYYY-MM-DD"),
    count: Math.floor(Math.random() * 80) + 40,
  })),
};

// 模拟用户统计数据
const mockUserStats = {
  total: 1520,
  activeUsers: 1235,
  trend: Array.from({ length: 30 }, (_, i) => ({
    date: dayjs()
      .subtract(29 - i, "days")
      .format("YYYY-MM-DD"),
    count: Math.floor(Math.random() * 200) + 100,
  })),
  genderDistribution: [
    { gender: "男", count: 854 },
    { gender: "女", count: 666 },
  ],
  ageDistribution: [
    { ageRange: "18-24", count: 450 },
    { ageRange: "25-30", count: 620 },
    { ageRange: "31-35", count: 320 },
    { ageRange: "36-40", count: 98 },
    { ageRange: "40+", count: 32 },
  ],
  regionDistribution: [
    { region: "中国-广东", count: 320 },
    { region: "中国-浙江", count: 250 },
    { region: "中国-江苏", count: 180 },
    { region: "中国-北京", count: 150 },
    { region: "中国-上海", count: 130 },
    { region: "中国-四川", count: 90 },
  ],
};
ChartJS.register(
  ArcElement,
  BarElement,
  LineElement,
  CategoryScale,
  LinearScale,
  PointElement,
  Title,
  Tooltip,
  Legend
);

const Dashboard = () => {
  const [orderStats, setOrderStats] = useState(mockOrderStats);
  const [fortuneStats, setFortuneStats] = useState(mockFortuneStats);
  const [ys,setYs]=useState([])
  const [userStats, setUserStats] = useState(mockUserStats);
  const [dateRange, setDateRange] = useState([
    dayjs().subtract(30, "days"),
    dayjs(),
  ]);
  console.log(mockUserStats, "mo");
  const fetchOrderStats = async (startDate, endDate) => {
    try {
      const response = await axios.get(
        "http://localhost:5000/userfortune/orders",
        {
          params: {
            startDate: startDate.format("YYYY-MM-DD"),
            endDate: endDate.format("YYYY-MM-DD"),
          },
        }
      );
      // console.log(response.data)
      let { data } = response;
      // setOrderStats(response.data);
      const convertedTrend = data.trend.map((item) => ({
        date: item.date.split("T")[0], // 或 item.date.substring(0, 10)
        count: item.count,
      }));
      data.trend = convertedTrend;
      // console.log(data, "data");
      setOrderStats(data);
    } catch (error) {
      console.error("Error fetching order stats:", error);
    }
  };

  const fetchFortuneStats = async (startDate, endDate) => {
    try {
      const response = await axios.get("http://localhost:5000/userfortune/fortunes", {
        params: {
          startDate: startDate.format("YYYY-MM-DD"),
          endDate: endDate.format("YYYY-MM-DD"),
        },
      });
      setFortuneStats(response.data);
      console.log(response.data,'for')
    } catch (error) {
      console.error("Error fetching fortune stats:", error);
    }
  };
  const getys = async (startDate, endDate) => {
    try {
      const response = await axios.get("http://localhost:5000/userfortune/getys", {
        // params: {
        //   startDate: startDate.format("YYYY-MM-DD"),
        //   endDate: endDate.format("YYYY-MM-DD"),
        // },
      });
      setYs(response.data.data);
      console.log(response.data.data,'for')
    } catch (error) {
      console.error("Error fetching fortune stats:", error);
    }
  };
  const fetchUserStats = async (startDate, endDate) => {
    try {
      const response = await axios.get(
        "http://localhost:5000/userfortune/users",
        {
          params: {
            startDate: startDate.format("YYYY-MM-DD"),
            endDate: endDate.format("YYYY-MM-DD"),
          },
        }
      );
      console.log(response.data,'yonghu')
      setUserStats(response.data);
    } catch (error) {
      console.error("Error fetching user stats:", error);
    }
  };

  useEffect(() => {
    fetchOrderStats(dateRange[0], dateRange[1]);
    fetchFortuneStats(dateRange[0], dateRange[1]);
    fetchUserStats(dateRange[0], dateRange[1]);
    getys()

    // 动态加载 china.json 并初始化 ECharts 地图
    fetch("/china.json")
      .then((response) => response.json())
      .then((chinaMap) => {
        const chartDom = document.getElementById("regionMap");
        if (!chartDom) return; // 防止 chartDom 未找到
        const myChart = echarts.init(chartDom);
        echarts.registerMap("china", chinaMap);

        const option = {
          title: { text: "用户地域分布", left: "center" },
          tooltip: { trigger: "item" },
          visualMap: {
            min: 0,
            max: 100,
            left: "left",
            top: "bottom",
            text: ["高", "低"],
            calculable: true,
          },
          series: [
            {
              name: "用户数量",
              type: "map",
              map: "china",
              roam: true,
              label: { show: true },
              data: userStats.regionDistribution.map((item) => ({
                name: item.region.split("-")[1] || item.region, // 提取省份名称
                value: item.count,
              })),
            },
          ],
        };
        myChart.setOption(option);

        // 清理 ECharts 实例
        return () => myChart.dispose();
      })
      .catch((error) => {
        console.error("Error loading china.json:", error);
      });
  }, [dateRange, userStats.regionDistribution]);

  const handleDateRangeChange = (dates) => {
    if (dates) {
      setDateRange(dates);
    }
  };

  const orderStatusData = {
    labels: orderStats.statusDistribution.map((item) => item.status),
    datasets: [
      {
        label: "订单状态分布",
        data: orderStats.statusDistribution.map((item) => item.count),
        backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
      },
    ],
  };

  const fortuneTypeData = {
    labels: fortuneStats.typeDistribution.map((item) => item.fortune_type),
    datasets: [
      {
        label: "测算类型分布",
        data: fortuneStats.typeDistribution.map((item) => item.count),
        backgroundColor: ["#FF6384", "#36A2EB", "#FFCE56"],
      },
    ],
  };

  const orderTrendData = {
    labels: orderStats.trend.map((item) =>
      dayjs(item.date).format("YYYY-MM-DD")
    ),
    datasets: [
      {
        label: "订单趋势",
        data: orderStats.trend.map((item) => item.count),
        borderColor: "#36A2EB",
        fill: false,
      },
    ],
  };

  const fortuneTrendData = {
    labels: ys.map((item) =>{
      console.log(item,'213')
      return dayjs(item.data).format("YYYY-MM-DD")
    }
    
      
    ),
    datasets: [
      {
        label: "营收",
        data: ys.map((item) => item.price),
        borderColor: "#FF6384",
        fill: false,
      },
    ],
  };

  const userTrendData = {
    labels: userStats.trend.map((item) =>
      dayjs(item.date).format("YYYY-MM-DD")
    ),
    datasets: [
      {
        label: "用户趋势",
        data: userStats.trend.map((item) => item.count),
        borderColor: "#FFCE56",
        fill: false,
      },
    ],
  };

  const genderData = {
    labels: userStats.genderDistribution.map((item) => item.sex),
    datasets: [
      {
        label: "性别分布",
        data: userStats.genderDistribution.map((item) => item.count),
        backgroundColor: ["#36A2EB", "#FF6384"],
      },
    ],
  };

  const ageData = {
    labels: userStats.ageDistribution.map((item) => item.ageRange),
    datasets: [
      {
        label: "年龄分布",
        data: userStats.ageDistribution.map((item) => item.count),
        backgroundColor: [
          "#FF6384",
          "#36A2EB",
          "#FFCE56",
          "#4BC0C0",
          "#9966FF",
        ],
      },
    ],
  };

  return (
    <div style={{ padding: "20px" }}>
      {/* <h1 style={{ textAlign: "center", marginBottom: "20px" }}>
        数据可视化大屏
      </h1> */}
      {/* <RangePicker
        value={dateRange}
        onChange={handleDateRangeChange}
        style={{ marginBottom: "20px" }}
      /> */}
      <div style={{ display: "flex", flexWrap: "wrap", gap: "20px" }}>
        <Card title="订单统计" style={{ width: 300 }}>
          <p>总订单数: {orderStats.total}</p>
          <Pie data={orderStatusData} />
        </Card>
        <Card title="测算统计" style={{ width: 300 }}>
          <p>总测算数: {fortuneStats.total}</p>
          <Pie data={fortuneTypeData} />
        </Card>
        <Card title="用户统计" style={{ width: 300 }}>
          <p>总用户数: {userStats.total}</p>
          <p>活跃用户数: {userStats.activeUsers}</p>
        </Card>
        <Card title="订单趋势" style={{ width: 600 }}>
          <Line data={orderTrendData} />
        </Card>
        <Card title="每日营收" style={{ width: 600 }}>
          <Line data={fortuneTrendData} />
        </Card>
        <Card title="用户趋势" style={{ width: 600 }}>
          <Line data={userTrendData} />
        </Card>
        <Card title="性别分布" style={{ width: 300 }}>
          <Bar data={genderData} />
        </Card>
        <Card title="年龄分布" style={{ width: 300 }}>
          <Bar data={ageData} />
        </Card>
      </div>
    </div>
  );
};

export default Dashboard;
